import 'dart:convert';

import 'package:ble_measure_plugin/devices/base_device_model.dart';
import 'package:ble_measure_plugin/utils/ext.dart';
import 'package:ble_measure_plugin/utils/logs.dart';

import '../ble_measure_plugin.dart';
import '../model/tem_model.dart';

class KangtaiTempDeviceModel extends BaseDeviceMeasureModel {
  @override
  String get serviceUuid => "0000ff12-0000-1000-8000-00805f9b34fb";

  @override
  String get characteristicWriteable => "0000ff01-0000-1000-8000-00805f9b34fb";

  @override
  String get characteristicReadable => "0000ff02-0000-1000-8000-00805f9b34fb";

  EventHandlerMap<TemModel>? _resultHandler;
  EventHandlerMap<String>? _errorHandler;

  void addListener({
    EventHandlerMap<TemModel>? resultListener,
    EventHandlerMap<String>? error,
  }) {
    _resultHandler = resultListener;
    _errorHandler = error;
  }

  @override
  void onOpenFail() {
    super.onOpenFail();
  }

  @override
  void onStartConnect() {
    super.onStartConnect();
  }

  @override
  void onOpenSuccess() {
    super.onOpenSuccess();
  }

  @override
  void onStartOpen() {
    super.onStartOpen();
  }

  @override
  void onReceiveData(List<String> data) {
    var state = const Utf8Codec().decode([int.parse(data[3], radix: 16)]);

    if (data[4] != '54' && data[4] != '45') {
      if (data[5] != '54' && data[5] != '45') {
        var temp = data.sublist(4).hexToAscii.replaceAll("C", "");
        // Log.d("receiveTemp===>${double.parse(temp)}");
        if(_resultHandler!=null){
          _resultHandler!(TemModel(temValue: "${double.parse(temp)}",measureType: state));
        }
      } else {
        var errorCode = data.sublist(5).hexToAscii;
        var msg = errorMsg(errorCode, int.parse(state));
        if(_errorHandler!=null){
          _errorHandler!("$errorCode:$msg");
        }
        // Log.d("receiveState===>${errorCode}");
      }
    } else {
      var errorCode = data.sublist(4).hexToAscii;
      var msg = errorMsg(errorCode, int.parse(state));
      if(_errorHandler!=null){
        _errorHandler!("$errorCode:$msg");
      }

    }
  }

  String errorMsg(String code, int state) {
    var msg = "";
    if (state == 0 || state == 2) {
      if (code.trim() == 'TaLo') {
        msg = "环境温度低于 0.1°C";
      }
      if (code.trim() == 'TaHi') {
        msg = "环境温度高于 40°C";
      }
      if (code.trim() == 'TbLo') {
        msg = "目标温度低于 32°C";
      }
      if (code.trim() == 'TbHi') {
        msg = "示目标温度高于 43°C";
      }
      Log.d("receiveState222===>${code}");

    }
    if (state == 1 || state == 3) {
      if (code == "TaLo") {
        msg = "环境温度低于 0.1°C";
      }
      if (code == "TaHi") {
        msg = "环境温度高于 40°C";
      }
      if (code == "TbLo") {
        msg = "目标温度低于 0.1°C";
      }
      if (code == "TbHi") {
        msg = "目标温度高于 100°C";
      }
    }
    return msg;
  }
}
